{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def permute(values):\n",
    "    n = len(values)\n",
    "    \n",
    "    # i: position of pivot\n",
    "    for i in reversed(range(n - 1)):\n",
    "        if values[i] < values[i + 1]:\n",
    "            break\n",
    "    else:\n",
    "        # very last permutation\n",
    "        values[:] = reversed(values[:])\n",
    "        return values\n",
    "    \n",
    "    # j: position of the next candidate\n",
    "    for j in reversed(range(i, n)):\n",
    "        if values[i] < values[j]:\n",
    "            # swap pivot and reverse the tail\n",
    "            values[i], values[j] = values[j], values[i]\n",
    "            values[i + 1:] = reversed(values[i + 1:])\n",
    "            break\n",
    "            \n",
    "    return values"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n",
      "[1, 2, 4, 3]\n",
      "[1, 3, 2, 4]\n",
      "[1, 3, 4, 2]\n",
      "[1, 4, 2, 3]\n",
      "[1, 4, 3, 2]\n",
      "[2, 1, 3, 4]\n",
      "[2, 1, 4, 3]\n",
      "[2, 3, 1, 4]\n",
      "[2, 3, 4, 1]\n",
      "[2, 4, 1, 3]\n",
      "[2, 4, 3, 1]\n",
      "[3, 1, 2, 4]\n",
      "[3, 1, 4, 2]\n",
      "[3, 2, 1, 4]\n",
      "[3, 2, 4, 1]\n",
      "[3, 4, 1, 2]\n",
      "[3, 4, 2, 1]\n",
      "[4, 1, 2, 3]\n",
      "[4, 1, 3, 2]\n",
      "[4, 2, 1, 3]\n",
      "[4, 2, 3, 1]\n",
      "[4, 3, 1, 2]\n",
      "[4, 3, 2, 1]\n",
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "x = [4, 3, 2, 1]\n",
    "for i in range(25):\n",
    "    print(permute(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['F', 'A', 'E', 'D']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "permute(list('FADE'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
